<template>
  <div class="page-container" v-loading="loading">
    <div class="add-wrap">
      <!-- <div class="header-section">
        <Breadcrumb :titles="titles"></Breadcrumb>
        <div class="title">
          数据月份：
          <el-date-picker
            v-model="select"
            type="month"
            @change="changeMonth"
            :clearable="false"
            placeholder="选择月"
          >
          </el-date-picker>
        </div>
      </div> -->

      <div class="search_header">
        <div class="search_header_left">
          <el-button
            icon="el-icon-plus"
            @click="addProject"
            v-has="'enterpriseEconomic:add'"
            >新增企业</el-button
          >
          <el-button
            icon="el-icon-download"
            @click="downloadFile"
            v-has="'enterpriseEconomic:export'"
            >下载数据</el-button
          >
          <!-- <el-button
          icon="el-icon-back"
          @click="downloadFile"
          v-has="'enterpriseEconomic:import'"
          >导入数据</el-button
        >
        <el-button
          @click="downloadFile"
          v-has="'enterpriseEconomic:export'"
          >数据模版下载</el-button
        > -->
        </div>

        <div class="search_header_right">
          <el-input
            placeholder="请输入企业名称"
            v-model="parameter.name"
            @keydown.enter.native="search"
            clearable
            @clear="search"
          >
            <span
              @click="search"
              slot="suffix"
              style="display: inline-block"
            >
              <Icon
                title="搜索"
                name="sousuo"
                color="#A7ADB5"
                font-size="20"
              />
            </span>
          </el-input>
          <el-date-picker
            v-model="currentSelect"
            type="month"
            @change="changeYearMonth"
            clearable
            placeholder="选择月"
            @clear="search"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
          <!-- <el-select
          placeholder="是否规上企业"
          v-model="parameter.enterpriseFlag"
          clearable
          @change="search"
          @clear="search"
        >
          <el-option
            v-for="item in isScaleEnterpriseOptions"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select> -->
        </div>
      </div>

      <div class="table-section">
        <el-table
          :data="tableData"
          :header-cell-style="{
            background: '#F2F6FB',
            color: ' #6B767D'
          }"
          height="100%"
        >
          <el-table-column
            label="企业名称"
            prop="name"
            width="280"
            show-overflow-tooltip
          />
          <el-table-column
            label="统一社会信用代码"
            prop="socialCode"
            width="200"
            show-overflow-tooltip
          />
          <el-table-column
            label="类型"
            prop="type"
            width="80"
            show-overflow-tooltip
          />
          <el-table-column
            label="上规情况"
            prop="enterpriseFlag"
          >
            <template slot-scope="scope">
              <el-input
                :disabled="isBeforeSelectedMonth()"
                v-model="scope.row.situation"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="上规时间"
            prop="enterpriseFlag"
            width="150"
          >
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.enterpriseTime"
                type="date"
                placeholder="选择日期"
                style="width: 140px"
                :disabled="isBeforeSelectedMonth()"
              ></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="累计产值(万元)">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.industryValue"
                type="number"
                :disabled="isBeforeSelectedMonth()"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="累计营收(万元)">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.revenue"
                type="number"
                :disabled="isBeforeSelectedMonth()"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="累计税收(万元)">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.tax"
                type="number"
                :disabled="isBeforeSelectedMonth()"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="更新时间"
            prop="enterpriseFlag"
            width="150"
          >
            <template slot-scope="scope">
              {{ scope.row.updateTime }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="操作" width="240">
            <template slot-scope="scope">
              <el-button
                @click="editProject(scope.row)"
                type="text"
                style="color: #00baff; font-weight: 400"
                v-has="'enterpriseEconomic:edit'"
                >编辑</el-button
              >
              <el-button
                @click="deleteProject(scope.row)"
                type="text"
                style="color: #ff5b5b; font-weight: 400"
                v-has="'enterpriseEconomic:delete'"
                >删除
              </el-button>
            </template>
          </el-table-column> -->
        </el-table>
      </div>
    </div>
    <div class="line">
      <el-button @click="saveInfo" class="save-btn"
        >保存</el-button
      >
    </div>

    <AddEnterpriseEconomicDialog
      :visible.sync="showDialog"
      :title="title"
      :currentData="currentData"
      :isDetail="isDetail"
      :isEdit="isEdit"
      :year="parameter.year"
      :month="parameter.month"
      @confirm="handleSubmit"
    />
  </div>
</template>

<script>
import Breadcrumb from '@/components/breadcrumb'
import dayjs from 'dayjs'
import {
  enterpriseEconomicQuery,
  deleteEnterpriseEconomic,
  downloadEnterpriseEconomic,
  enterpriseEconomicMonthQuery,
  saveEnterpriseEconomicList,
  addEnterpriseEconomic
} from '@/api/dataManagement'
import {
  isScaleEnterpriseOptions,
  enterpriseYearMonthOptions
} from '@/utils/project/data'
import Icon from '@/components/icon'
import { downloadBlobFile } from '@/utils/download'
import { STATIC_FILE_URL } from '@/api/config'
import AddEnterpriseEconomicDialog from './components/addEnterpriseEconomicDialog.vue'
import { isAfterMonth } from '@/utils/datetime'

export default {
  // props: {
  //   title: String,
  //   projectId: String
  // },
  components: {
    Breadcrumb,
    Icon,
    AddEnterpriseEconomicDialog
  },
  data() {
    return {
      tableData: [],
      select: '',
      parameter: {
        name: '',
        pageIndex: 1,
        pageSize: 999
      },
      loading: false,
      currentSelect: '',
      showDialog: false,
      currentData: {
        pkid: '',
        name: '',
        socialCode: '',
        type: '',
        enterpriseId: ''
      },
      isDetail: false,
      isEdit: false,
      title: '',
      currentNewMonth: '',
      pickerOptions: {
        disabledDate: (date) => {
          return isAfterMonth(date, new Date())
        }
      }
    }
  },
  computed: {
    titles() {
      return [this.title]
    },
    isScaleEnterpriseOptions() {
      return isScaleEnterpriseOptions
    },
    enterpriseYearMonthOptions() {
      return enterpriseYearMonthOptions
    }
  },
  async mounted() {
    const res = await enterpriseEconomicMonthQuery()
    if (res.success) {
      this.currentSelect = dayjs(res.data).format('YYYY-M')
      this.currentNewMonth = JSON.parse(
        JSON.stringify(this.currentSelect)
      )
    }

    // const date = new Date()
    // this.currentSelect = dayjs(date).format('YYYY-M')
    const year = this.currentSelect.split('-')[0]
    const month = this.currentSelect.split('-')[1]
    this.parameter.year = year
    this.parameter.month = month
    this.searchInfo()
  },
  methods: {
    changeYearMonth() {
      this.parameter.pageIndex = 1
      if (this.currentSelect) {
        const select = dayjs(this.currentSelect).format(
          'YYYY-MM-DD'
        )
        const obj = this.getYearAndMonth(select)
        this.parameter.year = obj.year
        this.parameter.month = obj.month
      } else {
        this.parameter.year = ''
        this.parameter.month = ''
      }
      const selectedDate = dayjs(this.currentSelect)
      const lastMonth = dayjs().subtract(1, 'month')
      this.isBefore =
        selectedDate.isBefore(lastMonth, 'month') &&
        this.parameter.month !== '01'

      this.searchInfo()
    },
    getYearAndMonth(dateStr) {
      const [year, month] = dateStr.split('-')
      return {
        year: year,
        month: month.startsWith('0')
          ? month.substring(1)
          : month
      }
    },
    isBeforeSelectedMonth() {
      const selectedMonth = dayjs(
        this.currentSelect,
        'YYYY-M'
      )
      const targetDate = dayjs(
        this.currentNewMonth,
        'YYYY-M'
      )
      return selectedMonth.isBefore(targetDate, 'month')
    },
    search() {
      this.parameter.keywords =
        this.parameter.keywords?.trim?.() || ''
      // this.parameter.pageIndex = 1
      this.searchInfo()
    },
    searchInfo() {
      enterpriseEconomicQuery(this.parameter)
        .then((res) => {
          if (res.success) {
            this.tableData = res.data.list
          } else {
            this.$message.error(res.message || '查询失败')
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    saveInfo() {
      if (!this.currentSelect) {
        this.$message.error('请选择月份')
        return
      }

      const arr = this.tableData.map((item) => {
        return {
          ...item,
          year: this.currentSelect.split('-')[0],
          month: this.currentSelect.split('-')[1],
          enterpriseTime: item.enterpriseTime
            ? dayjs(item.enterpriseTime).format(
                'YYYY-MM-DD'
              )
            : ''
        }
      })
      const params = {
        data: arr
      }
      saveEnterpriseEconomicList(params)
        .then((res) => {
          if (res.success) {
            this.$message.success('保存成功')
            this.searchInfo()
          } else {
            this.$message.error(res.message || '保存失败')
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    downloadFile() {
      this.btnLoading = true
      downloadFixedInfo(this.parameter)
        .then((res) => {
          downloadBlobFile(res, '固投信息表.xlsx')
        })
        .catch((err) => {
          this.$message.error('下载失败')
        })
        .finally(() => {
          this.btnLoading = false
        })
    },

    addProject() {
      this.showDialog = true
      this.isDetail = false
      this.isEdit = false
      this.currentData = Object.assign(
        {},
        this.$options.data().currentData
      )
      this.title = '新增'
    },

    // 编辑
    editProject(row) {
      this.showDialog = true
      this.isDetail = false
      this.currentData = row
      this.isEdit = true
      this.title = '编辑'
    },

    // 处理dialog确认事件
    async handleSubmit(formData) {
      try {
        const res = await addEnterpriseEconomic(formData)
        if (res.success) {
          this.$message.success(
            formData.pkid ? '编辑成功' : '新增成功'
          )
          this.showDialog = false
          this.searchInfo()
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        console.error('保存失败:', error)
        this.$message.error('保存失败，请重试')
      }
    },

    // 删除项目
    deleteProject(row) {
      this.$confirm(
        '此操作将永久删除该企业，是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          deleteEnterpriseEconomic(row.pkid).then((res) => {
            if (res.success) {
              this.$message.success('删除成功')
              if (
                this.total % 10 === 1 &&
                this.parameter.pageIndex ===
                  parseInt(this.total / 10) + 1 &&
                this.parameter.pageIndex !== 1
              ) {
                this.parameter.pageIndex -= 1
              }
              this.searchInfo()
            } else {
              this.$message.error(res.message)
            }
          })
        })
        .catch((error) => {
          this.$message.info('已取消删除')
        })
    },
    downloadFile() {
      this.btnLoading = true
      downloadEnterpriseEconomic(this.parameter)
        .then((res) => {
          downloadBlobFile(res, '企业经济指标信息表.xlsx')
        })
        .catch((err) => {
          this.$message.error('下载失败')
        })
        .finally(() => {
          this.btnLoading = false
        })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/table.scss';
// @import '~@/assets/css/form.scss';

.page-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px 10px;
}

.add-wrap {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #fff;

  // .body {
  //   width: 100%;
  //   display: flex;
  //   flex: 1;
  //   overflow: hidden;
  //   box-sizing: border-box;
  //   padding: 20px 10px;
  // }

  .title {
    margin: 15px 0;
  }

  .search_header_left {
    align-items: center;
    column-gap: 16px;

    .tips {
      font-size: 14px;
      color: #c93f3f;
    }
  }
}

.line {
  position: sticky;
  bottom: 0;
  width: calc(100% - 40px);
  padding-left: 30%;
  margin: 0 auto;
  right: 15px;
  background: #fff;
  border-top: 1px solid #eee;
  padding: 10px 0;
  display: flex;
  justify-content: center;
  z-index: 10;
}

.save-btn {
  background: #497fa3;
  border: 1px solid #497fa3;
  width: 104px;
  color: white;
  font-size: 14px;
  width: 104px;
  height: 34px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 10px auto;
}

.table-section {
  flex: 1;
  overflow: hidden;
}

.table-section ::v-deep .el-table__body-wrapper {
  overflow-y: auto !important;
}

// ::v-deep .el-input__inner {
//   max-width: 150px;
// }

.upload-container {
  position: relative;

  .image-preview {
    position: relative;
    display: inline-block;

    .delete-circle {
      position: absolute;
      top: 4px;
      right: 4px;
      width: 16px;
      height: 16px;
      background-color: #ff4d4f;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      color: white;
      font-size: 12px;

      &:hover {
        background-color: #ff7875;
      }
    }
  }

  .file-preview {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    max-width: 150px;

    .file-name {
      flex: 1;
      word-break: break-all;
      white-space: normal;
      line-height: 1.2;
    }

    .delete-circle {
      width: 16px;
      height: 16px;
      background-color: #ff4d4f;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      color: white;
      font-size: 12px;
      flex-shrink: 0;
      margin-top: 2px;

      &:hover {
        background-color: #ff7875;
      }
    }
  }
}
</style>
